import 'package:citiesocial/_include.dart';
import 'package:citiesocial/ui/account/my_address.dart';
import 'package:citiesocial/widgets/f4system/my_drop_down_button.dart';

class Payment extends BaseStatefulWidget {
  final CartEntity _cartEntity;
  Payment(this._cartEntity);
  @override
  State<StatefulWidget> createState() => _PaymentState();
}

class _PaymentState extends BaseState<Payment> {
  final _payTypes = ['在线支付'];

  AddressEntity _defaultAddress;
  String _payType;
  var _payWay = 2; //1-微信 2-支付宝

  _PaymentState();

  void _loadDefaultAddress() {
    HttpManager.defaultAddress(Configs.userId, Configs.userToken,
            context: context)
        .then((address) {
      _defaultAddress = address;
      setState(() {});
    });
  }

  void _goPay() {
    var method;
    if (_payWay == 1) {
      method = 'wechat';
      Toast.show(context, '微信支付申请中');
      return;
    } else {
      method = 'alipay';
    }
    LoadingDialog.show(context);
    HttpManager.sureOrder(
            Configs.userId,
            Configs.userToken,
            Configs.email,
            widget._cartEntity.total,
            '$_payWay',
            '${_defaultAddress.address_id}',
            context: context)
        .then((order) {
      LoadingDialog.dismiss(context).then((_) {
        _pay(method, widget._cartEntity.total, order.order_sn);
      });
    });
  }

  void _pay(String method, String amount, String order) {
    Toast.show(context, '正在打开支付……');
    BaseState.platform.invokeMethod('$method', {
      //alipay wechat
      'amount': '$amount',
      'merchantReference': '$order',
      'productName': 'cicci',
      'callbackUrl': 'http://citiesocial.zadtek.com/interface.php',
    }).then((result) {
      //  paid  unpaid  server  pending
      print(result);
      if ('paid' == result) {
        Toast.show(context, '支付成功').then((_) {
          Navigator.maybePop(context, '1');
        });
      } else if ('unpaid' == result) {
        Toast.show(context, '未支付').then((_) {
          Navigator.maybePop(context, '0');
        });
      } else {
        Toast.show(context, '订单确认中').then((_) {
          Navigator.maybePop(context, '0');
        });
      }
    });
  }

  @override
  void initState() {
    Future.delayed(Configs.loadDelay, () {
      _loadDefaultAddress();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _payType = _payTypes[0];
    final widgets = List<Widget>();
    widgets.add(Container(
      child: GestureDetector(
        child: ItemMenu2(
          title:
              '${_defaultAddress?.name ?? ''}\t${_defaultAddress?.mobile ?? ''}',
          subtitle: '${_defaultAddress?.address ?? ''}',
          leftIcon: 'imgs/location.png',
          rightIcon: 'imgs/js_tabs_secondscreen_img_disclosure.png',
        ),
        onTap: () {
          Navigator.push<AddressEntity>(
                  context, MaterialPageRoute(builder: (_) => MyAddress(true)))
              .then((address) {
            if (address != null) {
              setState(() {
                _defaultAddress = address;
              });
            }
          });
        },
      ),
      margin: EdgeInsets.only(bottom: 10.0),
    ));
    widgets.add(Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          child: Text(
            '付款方式',
            style: TextStyle(fontSize: 16.0),
          ),
          margin: EdgeInsets.only(right: 20.0),
        ),
        FixedDropdownButton<String>(
          value: _payType,
          style: TextStyle(
            fontSize: 16.0,
            color: Colors.black,
          ),
          items: _payTypes.map((pt) {
            return FixedDropdownMenuItem<String>(
              value: pt,
              child: ConstrainedBox(
                constraints: BoxConstraints.loose(Size.fromWidth(200.0)),
                child: Text(
                  '$pt',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            );
          }).toList(),
          onChanged: (item) {
            setState(() {
              _payType = item;
            });
          },
        ),
      ],
    ));
    widgets.addAll([
      ItemMenu(
        '支付宝',
        leftIcon: 'imgs/alipay_payment.png',
        rightIcon: _payWay == 2
            ? 'imgs/js_cells_img_selected.png'
            : 'imgs/js_cells_img_not_selected.png',
        leftIconEdge: 35.0,
        leftMargin: 20.0,
        rightMargin: 20.0,
        onTap: () {
          if (_payWay != 2) {
            setState(() {
              _payWay = 2;
            });
          }
        },
      ),
      ItemMenu(
        '微信支付',
        leftIcon: 'imgs/wechat_payment.png',
        rightIcon: _payWay == 1
            ? 'imgs/js_cells_img_selected.png'
            : 'imgs/js_cells_img_not_selected.png',
        leftIconEdge: 35.0,
        leftMargin: 20.0,
        rightMargin: 20.0,
        onTap: () {
          if (_payWay != 1) {
            setState(() {
              _payWay = 1;
            });
          }
        },
      ),
    ]);
    widgets.addAll(List<Widget>.generate(
      widget._cartEntity?.list?.length ?? 0,
      (index) => LongSquareGoodsItem(
            widget._cartEntity.list[index],
            imageEdge: 100.0,
            onTap: () {},
          ),
    ));
    return Scaffold(
      appBar: AppBarUtils.normal(context, '确认订单'),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: ListView(
                children: widgets,
              ),
            ),
            Container(
              color: Color.fromARGB(32, 20, 20, 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text('合计金额: ${widget._cartEntity.total}'),
                  GestureDetector(
                    child: Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 30.0, vertical: 15.0),
                      margin: EdgeInsets.only(left: 15.0),
                      child: Center(
                        child: Text(
                          '结 算',
                          style: TextStyle(color: Colors.white, fontSize: 15.0),
                        ),
                      ),
                      color: Configs.main,
                    ),
                    onTap: () {
                      _goPay();
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
